package com.mazong.serveresaa.controller;

import com.mazong.serveresaa.pojo.TbArticle;
import com.mazong.serveresaa.repo.MyElasticRepository;
import com.mazong.serveresaa.service.IElasticService;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/es")
public class ElasticController {

    @Autowired
    private IElasticService elasticService;

    @Autowired
    private MyElasticRepository elasticRepository;

    //-- 增加
    @GetMapping("/add")
    public String add(){
        elasticService.createIndex();
        List<TbArticle> list =new ArrayList<>();
        list.add(new TbArticle(1L,"XX0193","XX8064","少年听雨歌楼上，红烛昏罗帐。",1));
        list.add(new TbArticle(2L,"XX0210","XX7475","壮年听雨客舟中，江阔云低、断雁叫西风。",1));
        list.add(new TbArticle(3L,"XX0257","XX8097","而今听雨僧庐下，鬓已星星也。",1));
        list.add(new TbArticle(4L,"XX0259","XX8099","悲欢离合总无情，一任阶前、点滴到天明。",1));
        elasticService.saveAll(list);

        return "add ok";
    }

    //-- 查找全部
    @GetMapping("/all")
    public Iterator<TbArticle> all(){
        return elasticService.findAll();
    }

    //-- 根据ID查找
    @RequestMapping(value = "/find")
    public Object find(Long id) {
        return elasticRepository.findById(id);
    }

    //-- 删除
    @RequestMapping(value = "/delete")
    public Object delete(Long id) {
        elasticRepository.deleteById(id);
        return "delete";
    }

    //-- 全文查找
    @RequestMapping(value = "/findText")
    public Object findText() {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder("悲欢");
        return elasticRepository.search(builder);
    }

    @GetMapping("/update")
    public String update(){

        TbArticle article = new TbArticle(1L,"XX0193","XX8064","自古逢秋悲寂寥，我言秋日胜春朝。",1);
        elasticService.save(article);

        return "add ok";
    }

}
